window.onload = function (){
    initUser();
    findByItem(1);
}

/**
 * 显示用户登陆信息
 */
function initUser(){
    axios.get("/user/getLoginUser").then(resp =>{
       var info = resp.data;
       if(info == ""){
           $("userDiv").innerHTML = "你好，请先<a href='/login.html'>登陆</a>";
       }
       else{
           $("userDiv").innerHTML = "欢迎光临，"+info.name+
               " <a href='/custom/shop.html' style='margin-left: 100px'>查看购物车</a>";
       }
    });
}

/**
 * 动态条件分页查询商品
 * @param pageNO 页码
 */
function findByItem(pageNO){
    axios.get("/product/findByItem",{
        params: {
            pageNO,
            name:$("nameTxt").value,
            startDate:$("startTxt").value,
            endDate:$("endTxt").value
        }
    }).then(resp =>{
        var info = resp.data;
        var str = "";
        info.records.forEach(n =>{
           str += `<div style="width: 300px;height: 300px;text-align: center">
                <img src="/productImg/${n.imgPath}" width="200" height="200"><br>
                商品名：${n.name}<br>
                单价：${n.price}<br>
                已售出${n.sellNum}件<br>
                <input type="button" value="购买" onclick="buy(${n.id})">
            </div>`;
        });
        $("productDiv").innerHTML = str;

        var cutStr = "";
        for(var i=1;i<=info.pages;i++){
            cutStr += `<a style="margin-left: 10px;" href="javascript:findByItem(${i})">${i}</a>`;
        }
        $("cutPageDiv").innerHTML = cutStr;
    });
}

/**
 * 购买商品
 * @param productId 商品ID
 */
function buy(productId){
    axios.get("/shop/buy",{
        params: {productId}
    }).then(resp =>{
        if(resp.data == "ok"){
            location.href = "/custom/shop.html";
        }
        else{
            location.href = "/custom/login.html?errorInfo=noCustom";
        }
    })
}